<?php

class TextEmotionController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			)		
		);
	}
	public function actions()
	{
		return array(
				// captcha action renders the CAPTCHA image displayed on the contact page
				'captcha'=>array(
						'class'=>'CCaptchaAction',
						'backColor'=>0xFFFFFF,
				),
				// page action renders "static" pages stored under 'protected/views/site/pages'
				// They can be accessed via: index.php?r=site/page&view=FileName
				'page'=>array(
						'class'=>'CViewAction',
				),
		);
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($text_id)
	{
		$this->render('view',array(
			//'model'=>$this->loadModel($text_id),
		));
	}

	protected  function  analisar_arquivo($conteudo, $txt_lang)
	{
		ini_set("auto_detect_line_endings", true);
		print_r("text: ");
		//print_r(str_getcsv($conteudo, ";"));
		//print_r(explode(";" ,$conteudo));
		$arr_content = preg_split("/[\n;]+/" ,$conteudo);
		
		
		for($i = 0; $i< count($arr_content);$i+=5){
			$colecao = $arr_content[$i];
			
			$dados_colecao=Colecao::model()->find('descricao=?',array($colecao));
			if($dados_colecao  == NULL){
				$modelcolc=new Colecao;
				//print_r($modelcolc->attributes);
				//exit;
				$modelcolc->id = null;
				$modelcolc->descricao = $colecao;
				$modelcolc->save();
				$colecao_id= $modelcolc->attributes['id'];
			}
			else {
				$colecao_id= $dados_colecao->id;
			}
			$titulo = $arr_content[$i+1];
			$texto_cru = $arr_content[$i+4];
			$modeltxt=new Text;
			$modeltxt->id = null;
			$modeltxt->colecao_id = $colecao_id;
			$modeltxt->title = $titulo;
			$modeltxt->data_inc = date('Y-m-d');
			$modeltxt->conteudo = $texto_cru;		
			$modeltxt->save();
			
			$texto = $this->limpaTexto($texto_cru);
			$words = str_word_count($texto, 1); //explode(" ", );
			$listemotion = array();
			if ($txt_lang ==1){
				$lang = 'EN';
			}else {
				$lang = 'PT';
			}
			$dataemotion = Yii::app()->db->createCommand()
			->select("id, name")
			->from('tbl_emotion e')
			->where("e.lang = '".$lang."' ")
			->queryAll();
			
			foreach ($dataemotion as $key =>$emot){
				//print_r($emot);
				$emot['qtd'] = 0;
				$listemotion[$emot['id']] = $emot;
			}
			//	print_r($listemotion);
			$totalpalavras = 0;
			foreach ($words as $id => $word){
				if ($txt_lang ==1){
					if (!$this->stopword($word, 1)){
						$sword= CPorterStemmer::Stem($word);
						$stem_words[] = $sword;
						//print_r($sword);
						$emotions = Yii::app()->db->createCommand()
						->select('word, emotion_id')
						->from('tbl_word w')
						->join('tbl_emotion e', 'e.id=w.emotion_id')
						->where("(trim(upper(lemma)) like trim(upper(:word)) OR trim(upper(word)) like trim(upper(:word))) and e.lang = 'EN' ", array(':word'=>$sword))
						->queryRow();
			
						if (!empty($emotions)){
							$emotion_id = $emotions['emotion_id'];
							$listemotion[$emotion_id]['qtd'] = $listemotion[$emotion_id]['qtd'] +1;
						}
					}
				}else if($txt_lang ==2){
					if (!$this->stopword($word,2)){
						$sword = CPtPorterStemmer::Stem($word);
						$stem_words[] = $sword;
						//print_r($sword." ");
						$emotions = Yii::app()->db->createCommand()
						->select('word, emotion_id')
						->from('tbl_word w')
						->join('tbl_emotion e', 'e.id=w.emotion_id')
						->where("(trim(upper(lemma)) like trim(upper(:word)) OR trim(upper(word)) like trim(upper(:word))) and e.lang = 'PT' ", array(':word'=>$sword))
						->queryRow();
			
						if (!empty($emotions)){
							$emotion_id = $emotions['emotion_id'];
							$listemotion[$emotion_id]['qtd'] = $listemotion[$emotion_id]['qtd'] +1;
						}
			
					}
				}else{
					if (!$this->stopword($word, 3)){
						$sword = CEsStemmer::Stem($word);
						$stem_words[] = $sword;
						//print_r($sword);
						//echo(" ");
					}
				}
				$totalpalavras++;
		}
		
		
		
		foreach ($listemotion as $key => $value){
			$modelTxtEmot = new TextEmotion;
			$modelTxtEmot->id = null;
			$modelTxtEmot->text_id = $modeltxt->attributes['id'];
			$modelTxtEmot->emotion_id = $key;
			$modelTxtEmot->quantidade = $value['qtd']/$totalpalavras;
			$modelTxtEmot->save();
		}
		
		//die();
		//$modelCol=new Colecao;
		//$modelCol->
		
		} 

	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new TextEmotion;
		$model = new Text;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		//$model=new ContactForm;
		
		if(isset($_POST['Text']))
		{
			$model->attributes=$_POST['Text'];		
			
			
		 if (!empty($_FILES['Text']['name'])){
		 	Yii::import('application.extensions.upload.Upload');		
			$file = CUploadedFile::getInstance($model,'arquivo');
		 	$conteudo=file_get_contents($file->tempName);
		 	
				$this->analisar_arquivo($conteudo, $_POST['Text']['lang'] );
		}else{
			if (empty($_POST['Text']['texto'])){
				$this->render('create',array('model'=>$model));
			}
			print_r("passou2");
			$texto = $this->limpaTexto($_POST['Text']['texto']);
			$words = str_word_count($texto, 1); //explode(" ", );
				
			$listemotion = array();
			if ($_POST['Text']['lang'] ==1){
				$lang = 'EN';
			}else {
				$lang = 'PT';
			}
			$dataemotion = Yii::app()->db->createCommand()
			->select("id, name")
			->from('tbl_emotion e')
			->where("e.lang = '".$lang."' ")
			->queryAll();
				
			foreach ($dataemotion as $key =>$emot){
				//print_r($emot);
				$emot['qtd'] = 0;
				$listemotion[$emot['id']] = $emot;
			}
			print_r("passou3");
			//	print_r($listemotion);
			$totalpalavras = 0;
			foreach ($words as $id => $word){
				if ($_POST['Text']['lang'] ==1){
					if (!$this->stopword($word, 1)){
						$sword= CPorterStemmer::Stem($word);
						$stem_words[] = $sword;
						//print_r($sword);
						$emotions = Yii::app()->db->createCommand()
						->select('word, emotion_id')
						->from('tbl_word w')
						->join('tbl_emotion e', 'e.id=w.emotion_id')
						->where("(trim(upper(lemma)) like trim(upper(:word)) OR trim(upper(word)) like trim(upper(:word))) and e.lang = 'EN' ", array(':word'=>$sword))
						->queryRow();
		
						if (!empty($emotions)){
							$emotion_id = $emotions['emotion_id'];
							$listemotion[$emotion_id]['qtd'] = $listemotion[$emotion_id]['qtd'] +1;
						}
					}
				}else if($_POST['Text']['lang'] ==2){
					if (!$this->stopword($word,2)){
						$sword = CPtPorterStemmer::Stem($word);
						$stem_words[] = $sword;
						//print_r($sword." ");
						$emotions = Yii::app()->db->createCommand()
						->select('word, emotion_id')
						->from('tbl_word w')
						->join('tbl_emotion e', 'e.id=w.emotion_id')
						->where("(trim(upper(lemma)) like trim(upper(:word)) OR trim(upper(word)) like trim(upper(:word))) and e.lang = 'PT' ", array(':word'=>$sword))
						->queryRow();
		
						if (!empty($emotions)){
							$emotion_id = $emotions['emotion_id'];
							$listemotion[$emotion_id]['qtd'] = $listemotion[$emotion_id]['qtd'] +1;
						}
		
					}
				}else{
					if (!$this->stopword($word, 3)){
						$sword = CEsStemmer::Stem($word);
						$stem_words[] = $sword;
						//print_r($sword);
						//echo(" ");
					}
				}
				$totalpalavras++;
			}
		}
			if(isset($listemotion))
			{
				//print_r($listemotion);
				//salva texto
				$session=new CHttpSession;
				$session->open(); // Yii::app()->session['myVar']
				Yii::app()->session['title']=$_POST['Text']['title'];
				Yii::app()->session['listemotion']=$listemotion;
				Yii::app()->session['totwords']=$totalpalavras;
				$model->attributes=$listemotion;
			//	if($model->save())
					//$this->redirect(array('view','text_id'=>$model->text_id));
				$this->render('view',array('model'=>$model));
			}
			//$this->render('result',array('model'=>$model));
			//$this->redirect(array('result','model'=>$model));
				
			//$this->redirect('result');
			//	exit;
		}
		else{
			//$this->render('contact',array('model'=>$model));
			$this->render('create',array('model'=>$model));
		}
		
	
}
		

		

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['TextEmotion']))
		{
			$model->attributes=$_POST['TextEmotion'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('TextEmotion');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new TextEmotion('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TextEmotion']))
			$model->attributes=$_GET['TextEmotion'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return TextEmotion the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=TextEmotion::model()->findByPk($id); 
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param TextEmotion $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='text-emotion-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	protected  function limpaTexto($txt)
	{
		$beta=array(
				'a','a','a','a','a',
				'e','e','e','e',
				'i','i','i','i',
				'o','o','o','o','o',
				'u','u','u','u','c',
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," "," "," ",
				"","","","","",
				"","","","","",
		);
		$alfa=array(
				'á','à','ã','â','ä',
				'é','è','ê','ë',
				'í','ì','î','ï',
				'ó','ò','õ','ô','ö',
				'ú','ù','û','ü','ç',
				"\"","'","!","@","#",
				"$","%","&","*","(",
				")","+","}","]","=",
				"º","§","{","[","ª",
				"?","/","°","<",">",
				"\\","|",",",".",";",
				":","~","^","´","`","_",
				'0','1','2','3','4',
				'5','6','7','8','9'
		);
		//	print_r("<br>.........chegou.......1:".$txt);
		//$gama = strtolower($txt);
		//	print_r("<br>.........lower...2:".$gama);
		//$omega=str_replace($alfa,$beta,$gama);
		//	print_r(strtolower($txt));
		$omega=str_replace($alfa,$beta,$txt);
		//	print_r($omega. ":.....replace...........3");
		$pi=strip_tags($omega);
		$omega=stripcslashes($pi);
		return($omega);
	}
	protected  function limpaTexto2($txt)
	{
		$beta=array(
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," ",
				" "," "," "," "," "," "," ",
				"","","","","",
				"","","","","",
		);
		$alfa=array(
				"\"","'","!","@","#",
				"$","%","&","*","(",
				")","+","}","]","=",
				"º","§","{","[","ª",
				"?","/","°","<",">",
				"\\","|",",",".",";",
				":","~","^","´","`","_",
				'0','1','2','3','4',
				'5','6','7','8','9'
		);
			
		$gama = strtolower($txt);
		$omega=str_replace($alfa,$beta,$gama);
		$pi=strip_tags($omega);
		$omega=stripcslashes($pi);
		return($omega);
	}
	
	protected  function stopword($word, $l)
	{
		switch ($l):
		case 2:{
			$list = "a do acima ainda algo algum alguma algumas alguns alguém ambas ambos ao aos ao às apesar após aquela aquele aqueles aquilo as assim até à
					 cada caso cerca certa certo certos com como conforme contanto contra contudo cujo cujos da daquela daquelas daquele daqueles daquilo das
					 de dela delas dele deles demais desde dessa dessas desse desses desta destas deste destes devido diante disso dissonante diversas diversos
					 do dos dourada e ela elas ele eles em embora enquanto entanto entre entretanto então essa essas esse esses esta estas este estes exceto há
					 isso isto lhe lhes libre la las lo los mais mas me menos mesma mesmas mesmo mesmos meu meus mim minha minhas modo monte muita muitas muito muitos
					 na nada nas né nem nenhum nenhuma nessa ninguém no nos nossa nossas nosso nossos num numa não nós o obstante onde os ou outra outras outro outros
					 para pela pelas pelo pelos per perante pois por porque porquê portanto porém posto poucas pouco poucos pousada pra prá própria próprias próprio
					 próprios quais qual qualquer quando quantas quanto quantos quase que quem quer quê salvo se segundo sem sempre sendo sentido senão ser serpente
					 seu seus si sob sobre soda sua suas tais tal tanta tantas tanto tantos te teu teus ti toda todas todo todos tudo um uma umas vos uns vez você
					 vocês vossa várias vários vós sido sendo tido tendo havido havendo";
			$stop_words = explode(" ", $list);
			break;
		}
		case 1:{
			$stop_words = array("about", "above", "after", "all", "alone", "also", "am", "and", "as", "at", "because", "before", "beside", "besides", "between", "but", "by",
					"etc", "for", "i", "of", "on", "other", "others", "so", "than", "that", "though", "to", "too", "trough", "until", "me",
					"the",  "a", "an", "in", "is" , "it", "you", "your", "yours", "this", "with", "are", "have", "be", "at", "or",
					"was", "so", "if", "out", "not", "my", "myself");
			break;
		}
		case 3:{
			$list = "saber sabes  ser si siendo sin sobre sois solamente solo somos soy su sus también teneis tenemos tener tengo tiempo tiene tienen todo trabaja
						trabajais trabajamos trabajan trabajar trabajas trabajo tras tuyo ultimo un una unas uno unos usa usais usamos usan usar usas uso va vais valor vamos
						van vaya vosotras vosotros voy yo";
			$stop_words = explode(" ", $list);
			break;
		}
		endswitch;
	
		if(in_array($word, $stop_words)) {
			return(true);
		}else{
			return(false);
		}
			
	}
	
	
	protected  function bacalho()
	{
	
		$words = Yii::app()->db->createCommand()
		->select('w.id, word, name, lang')
		->from('tbl_word w')
		->join('tbl_emotion e', 'e.id=w.emotion_id')
		->queryAll();
	
		foreach ($words as $id => $word){
			if ($word['lang']== 'EN'){
				$sword= CPorterStemmer::Stem($word['word']);
	
			}else{
				$sword = CPtPorterStemmer::Stem($word['word']);
			}
	
			$command = Yii::app()->db->createCommand();
			$command->update('tbl_word', array(
					'lemma'=>$sword,
			), 'id=:id', array(':id'=>$word['id']));
			print_r($sword);
			echo("  ");
		}
		/*
			Yii::app()->db
		->createCommand("UPDATE list SET Status = 'R' WHERE ListId=:ListId OR RListID=:RListID")
		->bindValues(array(':ListId' => $_POST['ListId'], ':RListID' => $_POST['RListId']))
		->execute();*/
	}
	
}
